package org.cqc.component;

import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.filters.AddDefaultCharsetFilter;
import org.cqc.utils.JsonUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author caoqc
 * @Description: 拦截器
 * @date 2022/01/29 16:43:38
 */
@Slf4j
@Component
public class SimulatorInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        printRequest(request);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {

        printResponse(response);
    }

    private void printRequest(HttpServletRequest request) {
        String url = request.getRequestURI();
        String queryString = request.getQueryString();
        Map map = request.getParameterMap();
        log.info("请求地址:[{}]", url);
        log.info("请求参数:[{}]", queryString);
        log.info("请求内容:[{}]", JsonUtil.objectToJson(map));
    }


    private void printResponse(HttpServletResponse response) throws IOException {

        AddDefaultCharsetFilter.ResponseWrapper responseWrapper =
                new AddDefaultCharsetFilter.ResponseWrapper(response, "UTF-8");

        responseWrapper.toString();

        String result = response.getOutputStream().toString();


        log.info("返回结果:[{}]", JsonUtil.objectToJson(result));
    }

}
